package com.fzz.learning_forum.controller;

import com.fzz.learning_forum.domain.*;
import com.fzz.learning_forum.service.*;
import com.fzz.learning_forum.serviceImpl.*;
import com.github.pagehelper.PageInfo;
import com.vdurmont.emoji.EmojiParser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.Date;
import java.util.List;

import static java.lang.Math.random;

@Controller
public class UserController {

    @Autowired
    private UserService userService = new UserServiceImpl();

    @Autowired
    private CommentService commentService = new CommentServiceImpl();

    @Autowired
    private ArticleService articleService = new ArticleServiceImpl();

    @Autowired
    private ReplyService replyService=new ReplyServiceImpl();

    @Autowired
    private CourseService courseService=new CourseServiceImpl();

    @RequestMapping(value = "/user/")
    public String index(HttpServletRequest request) {
        return this.index(request, 1, 5);
    }

    // 分页查询文章
    @RequestMapping(value = "/page/{p}")
    public String index(HttpServletRequest request, @PathVariable("p") int page, @RequestParam(value = "count", defaultValue = "5") int count) {
        PageInfo<Article> articleList = articleService.selectArticleWithPage(page, count);
        HttpSession session = request.getSession();
        PageInfo<Course> courseList = courseService.selectAllCourse(page, count);
        session.setAttribute("courseList",courseList);
        session.setAttribute("articleList", articleList);
        session.removeAttribute("user_detail");
        List<Article> viewList = articleService.selectArticleByView();
        session.setAttribute("viewList",viewList);
        List<Article> recommendList = articleService.selectArticleByHitAndView();
        session.setAttribute("recommendList",recommendList);
        return "client/index";
    }

    // 根据id查询自己的文章
    @RequestMapping(value = "/userArticles/{p}/{id}")
    public String userArticles(HttpServletRequest request, @PathVariable("id") Integer id, @PathVariable(value = "p") int page, @RequestParam(value = "count", defaultValue = "5") int count) {

        PageInfo<Article> articleList = articleService.selectArticleWithPageById(page, count, id);
        HttpSession session = request.getSession();
        session.setAttribute("articles", articleList);
        session.setAttribute("user_detail","yes");
        List<Comment> commentList = commentService.selectNewComment(id);
        session.setAttribute("commentList",commentList);
        return "client/myDynamicState";
    }

    //修改用户信息
    @RequestMapping(value = "/user/editUserInfo")
    @ResponseBody
    public String editUserInfo(HttpSession session, User user) {
        Integer rows = userService.editUserInfo(user);
        if (rows > 0) {
            session.setAttribute("user", user);
            return "OK";
        }
        return "NO";
    }

    //根据tags模糊查询文章
    @RequestMapping(value = "/user/selectArticleByTags")
    public String selectArticleByTags(HttpServletRequest request, @RequestParam(value = "p", defaultValue = "1") int page, @RequestParam(value = "count", defaultValue = "5") int count, String tags) {

        PageInfo<Article> articleList = articleService.selectArticleByTags(page, count, tags);
        HttpSession session = request.getSession();
        session.setAttribute("articleList", articleList);
        return "client/index";
    }


    //发布界面
    @RequestMapping(value = "/user/publish")
    public String toPublish(HttpSession session) {
        session.removeAttribute("article");
        return "client/article_edit";
    }

    //发布动态
    @RequestMapping(value = "/user/publishArticl")
    @ResponseBody
    public String publishArticle(Article article) {

        article.setTags(article.getTags().substring(1, article.getTags().length()));
        article.setContent(EmojiParser.parseToAliases(article.getContent()));
        String url="/user/img/articleImg/";
        Integer num=(int)Math.ceil(random()*10);
        url+=num.toString();
        url+=".jpg";
        article.setArticle_img(url);
        article.setHit(0);
        article.setView(0);

        try {
            Integer rows = articleService.publishArticle(article);
            if (rows > 0) {
                return "OK";
            }
        }
        catch (Exception e)
        {
            System.out.println(e.getCause());
        }
        return "NO";
    }

    //根据id查询动态细节
    @RequestMapping(value = "/user/selectArticleDetail/{id}")
    public String selectarticleDetail(HttpServletRequest request, HttpSession session, @PathVariable("id") Integer id) {
        Article article = articleService.selectArticleDetail(id);
        List<Reply> replyList = replyService.selectReply(id);
        session.setAttribute("replyList",replyList);
        request.removeAttribute("comments");
        getArticleComments(request, article);
        if (article != null) {
            try{
                Integer view = article.getView();
                view+=1;
                articleService.updateArticleView(id, view);
            }
            catch (Exception e)
            {
                System.out.println(e.getCause());
            }
            session.setAttribute("article", article);
            return "client/articleDetails";
        }
        return "redirect:/user/";
    }

    // 查询文章的评论信息，并补充到文章详情里面
    private void getArticleComments(HttpServletRequest request, Article article) {
        // cp表示评论页码，commentPage
        String cp = request.getParameter("cp");
        cp = StringUtils.isBlank(cp) ? "1" : cp;
        request.setAttribute("cp", cp);
        PageInfo<Comment> comments = commentService.selectCommentWithPage(article.getId(), Integer.parseInt(cp), 3);

        request.setAttribute("cp", cp);
        request.setAttribute("comments", comments);
    }

    //转到修改动态信息
    @RequestMapping(value = "/user/toEditArticle/{id}")
    public String toEditArticle(HttpSession session, @PathVariable("id") Integer id) {
        Article article = articleService.selectArticleDetail(id);
        if (article != null) {
            session.setAttribute("article", article);
            return "client/article_edit";
        }

        return "redirect:/user/";
    }

    //修改动态信息
    @RequestMapping(value = "/user/editArticle")
    @ResponseBody
    public String editArticle(HttpSession session, Article article) {
        article.setTags(article.getTags().substring(1, article.getTags().length()));
        Integer rows = articleService.editArticle(article);
        if (rows > 0) {
            session.setAttribute("article", article);
            return "EOK";
        }
        return "ENO";
    }

    //根据id删除动态
    @RequestMapping(value = "/user/deleteArticle")
    @ResponseBody
    public String deleteArticle(Integer id) {
        Integer rows = articleService.deleteArticle(id);
        if (rows > 0) {
            return "OK";
        }
        return "NO";
    }
}
